package com.example.homeworkmutualevaluation.Service;

import com.example.homeworkmutualevaluation.Dao.FileDao;
import com.example.homeworkmutualevaluation.Entity.File;
import com.example.homeworkmutualevaluation.utils.UniqueId;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


@Service
public class FileService {
    @Resource
    private FileDao fileDao;

    public String upload(MultipartFile file) {
        if (file == null) return null;
        try {
            String fileName = file.getOriginalFilename();
            String fileId = UniqueId.next();
            fileDao.insert(fileId, fileName, file.getBytes());
            return fileId;
        } catch (IOException e) {
            return null;
        }
    }
    public void download(String id, HttpServletResponse response) {
        File file = fileDao.findById(id);
        if (file != null) {
            response.setHeader("content-disposition", "attachment; fileName=" +
                    URLEncoder.encode(file.getName(), StandardCharsets.UTF_8));
            try (ServletOutputStream out  = response.getOutputStream()) {
                out.write(file.getData());
                out.flush();
            } catch (IOException ignored) {}
        }
    }

    public void getImg(String id, HttpServletResponse response) {
        File file = fileDao.findById(id);
        if (file != null) {
            response.setContentType(MediaType.IMAGE_PNG_VALUE);
            response.setContentLength(file.getData().length);
            try (ServletOutputStream out = response.getOutputStream()) {
                out.write(file.getData());
                out.flush();
            } catch (IOException ignored) {}
        }
    }

    public String getFileName(String id) {
        return fileDao.findNameById(id);
    }
}
